﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace JVMTI_CONN_CONNECT
{
    static class Utils
    {
        public static Dictionary<string, string> ThreadIdToFriendlyNameMap(IEnumerable<JvmtiEvent> events)
        {
            var dict = new Dictionary<string, string>();
            var startedEvents = events.AsParallel<JvmtiEvent>().Where<JvmtiEvent>(o=>o.MethodName == JvmtiMethodEnum.ThreadStarted);
            //Not necessary. Probably faster to just loop.
            //events.Where<JvmtiEvent>(jevent => jevent.MethodName == JvmtiMethodEnum.ThreadStarted).Select<JvmtiEvent, KeyValuePair<string, string>>(jevent => new KeyValuePair<string, string>(jevent.ExtendedArguments.Object, jevent.ExtendedArguments.NameAssignment)).ForEach<KeyValuePair<string,string>>(new Action<KeyValuePair<string,string>>(o=>dict.Add(o.Key,o.Value)));
            foreach(var startEvent in startedEvents)
            {
                dict.Add(startEvent.SubjectThread, startEvent.ExtendedArguments.NameAssignment);
            }
            return dict;
            //beauty of dynamics.
        }

        //side effect for-each. Must stop chaining by returning void to avoid illegal state.
        public static void ForEach<T> (this IEnumerable<T> collection,Action<T> action)
        {
            foreach (T item in collection)
            {
                action(item);
            }
        }
    }
}
